import 'dart:io';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        brightness: Brightness.dark,
        primarySwatch: Colors.blue,
      ),
      home: new RouteListPage(),
    );
  }
}

class RouteListPage extends StatefulWidget {
  const RouteListPage({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _RouteListPageState();
  }
}

class _RouteListPageState extends State<RouteListPage> {
  List subjects = new List();
  String title;

  bool _loading = false;
  String _text = "";

  void loadData() async {
    try {
      HttpClient httpClient = new HttpClient();
      HttpClientRequest request = await httpClient.getUrl(Uri.parse(
        'https://api.douban.com/v2/movie/in_theaters?start=0&count=100&city=广州&apikey=0df993c66c0c636e29ecbb5344252a4a',
      ));
      //使用iPhone的UA
      request.headers.add('user-agent',
          'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1');
      //等待连接服务器（会将请求信息发送给服务器）
      HttpClientResponse response = await request.close();
      //读取相应内容
      _text = await response.transform(utf8.decoder).join();
      var _json = json.decode(_text);
      subjects.addAll(_json['subjects']);
      //输出相应头
      print(response.headers);

      //关闭client后，通过该client发起的所有请求终止
      httpClient.close();
    } catch (e) {
      _text = '请求失败 $e';
    } finally {
      setState(() {
        print('$_text');
        _loading = false;
        print(subjects);
      });
    }
  }

  getItem(var subject) {
    //演员列表
    var avatars = List.generate(subject['casts'].length, (int index) => new Container(
      margin: EdgeInsets.only(left: index == 0 ? 0 : 8),
      child: new CircleAvatar(
        backgroundColor: Colors.white10,
        backgroundImage: NetworkImage(subject['casts'][index]['avatars'] != null ? subject['casts'][index]['avatars']['small'] : ''),
      ),
    ));

    var row = new Container(
      margin: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
      child: new Row(
        children: <Widget>[
          new ClipRRect(
            borderRadius: BorderRadius.circular(4.0),
            child: Image.network(
              subject['images']['large'],
              width: 100,
              height: 150,
              fit: BoxFit.fill
            ),
          ),
          new Expanded(
            child: new Container(
              margin: EdgeInsets.only(left: 10),
              height: 150,
              alignment: Alignment.center,
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  new Text(
                    subject['title'],
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  new Text(
                    '豆瓣评分：${subject['rating']['average']}',
                    style: TextStyle(fontSize: 16),
                  ),
                  new Text(
                    "类型：${subject['genres'].join("、")}"
                  ),
                  new Text(
                    '导演：${subject['directors'][0]['name']}'
                  ),
                  new Container(
                    margin: EdgeInsets.only(top: 10),
                    child: new Row(
                      children: <Widget>[
                        new Text('主演：'),
                        new Row(
                          children: avatars,
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
    
    // return new ButtonTheme(
    //   padding: EdgeInsets.all(0),
    //   child: new FlatButton(
    //     onPressed: () {},
    //     child: row,
    //   ),
    // );

    return new Card(
      child: new ButtonTheme(
        padding: EdgeInsets.all(0),
        child: new FlatButton(
          child: row,
          onPressed: () {},
        ),
      ),
    );
  }

  getBody() {
    if (subjects.length != 0) {
      return ListView.builder(
          itemCount: subjects.length,
          itemBuilder: (BuildContext context, int index) {
            return getItem(subjects[index]);
          });
    } else {
      // 加载菊花
      return CupertinoActivityIndicator();
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: new Text('正在上映的电影'),
      ),
      body: new Center(
        child: getBody(),
      ),
    );
  }
}
